//
//  LoginController.m
//  collection
//
//  Created by 靖 张 on 12/4/11.
//  Copyright (c) 2011 Tsinghua University. All rights reserved.
//

#import "LoginController.h"
#import "BaseController.h"
#import "CollectionDataManager.h"
#import "MBProgressHUDHelper.h"
#import "AppDelegate.h"

@interface LoginController()

@property (retain, nonatomic) IBOutlet UITableView *contentTableView;
@property (nonatomic, strong)   IBOutlet    UITextField*    userNameTextField;
@property (nonatomic, strong)   IBOutlet    UITextField*    passwordTextField;
@property (nonatomic, retain) MBProgressHUD* indicatorView;

- (IBAction)onClickLoginButton:(id)sender;
- (IBAction)onClickCancelButton:(id)sender;

@end


@implementation LoginController

@synthesize contentTableView = _contentTableView;
@synthesize userNameTextField = _userNameTextField;
@synthesize passwordTextField = _passwordTextField;
@synthesize indicatorView = _indicatorView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    
    return self;
}

- (void)dealloc {
    self.userNameTextField  = nil;
    self.passwordTextField  = nil;
    self.indicatorView = nil;
    
    [_contentTableView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    self.contentTableView.backgroundColor = [UIColor clearColor];
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"all_bg"]];
    self.userNameTextField.text = @"CollectionMVP";
    self.passwordTextField.text = @"123456";
}

- (void)viewDidUnload
{
    [self setContentTableView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    self.userNameTextField  = nil;
    self.passwordTextField  = nil;
    self.indicatorView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"LoginCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.indentationLevel = 1;
        cell.indentationWidth = 15.0f;
    }
    
    // Configure the cell...
    // User name
    int startX = 80;
    if (indexPath.row == 0) {
        cell.textLabel.text = @"帐号：";
        CGRect frame;
        frame.origin.x      = startX;
        frame.origin.y      = 0;
        frame.size.width    = cell.frame.size.width - startX;
        frame.size.height   = cell.frame.size.height;
        self.userNameTextField.frame = frame;
        [cell addSubview:self.userNameTextField];
    }
    else if (indexPath.row == 1) {
        cell.textLabel.text = @"密码：";
        CGRect frame;
        frame.origin.x      = startX;
        frame.origin.y      = 0;
        frame.size.width    = cell.frame.size.width - startX;
        frame.size.height   = cell.frame.size.height;
        self.passwordTextField.frame = frame;
        [cell addSubview:self.passwordTextField];
    }
    
    return cell;
}

#pragma mark - Private methods

- (IBAction)onClickLoginButton:(id)sender {
    NSLog(@"Click login");
    
    [self.userNameTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    
    NSString* userName = self.userNameTextField.text;
    NSString* password = self.passwordTextField.text;
    
    // Check the user name and password
    BOOL res = YES;
    NSString* alertInfo = nil;
    if (userName == nil || [userName isEqualToString:@""]) {
        alertInfo = @"用户名不能为空";
        res = NO;
    }
    else if (password == nil || [password isEqualToString:@""]) {
        alertInfo = @"密码不能为空";
        res = NO;
    }
    else if (![userName isEqualToString:@"CollectionMVP"] ||
             ![password isEqualToString:@"123456"]) {
        alertInfo = @"密码错误，请重输";
        self.passwordTextField.text = @"";
        res = NO;
    }
    
    if (!res) {
        self.indicatorView = [MBProgressHUDHelper popUpMBProcessHUD:self.view delegate:nil];
        [MBProgressHUDHelper changeToMBFailedMode:self.indicatorView customMsg:alertInfo afterDelay:1.5f];
    }
    else {
        self.indicatorView = [MBProgressHUDHelper popUpMBProcessHUD:self.view delegate:nil];
        self.indicatorView.labelText = @"登录中";
        [self.indicatorView show:YES];
        
        [self.indicatorView hide:YES afterDelay:1.0f];
        [NSTimer scheduledTimerWithTimeInterval:1.0f
                                         target:self 
                                       selector:@selector(delayFinishedRefreshLoading)
                                       userInfo:nil
                                        repeats:NO];
    }
}

- (IBAction)onClickCancelButton:(id)sender {
    
    [self dismissModalViewControllerAnimated:YES];
}

- (void)delayFinishedRefreshLoading {
/*    
    if (self.indicatorView != nil) {
        [self.indicatorView hide:YES afterDelay:1.5f];
    }
*/
    [self dismissModalViewControllerAnimated:YES];
 // Do login
    //    [self dismissModalViewControllerAnimated:NO];
    CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
    sharedDataManager.currentLoginUser = [sharedDataManager cacheUserByUserID:1];
    
    BaseController* baseController = [[BaseController alloc] initWithNibName:@"BaseController" bundle:nil];
    //    [self.navigationController popViewControllerAnimated:NO];
    AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    //    [appDelegate.rootNavigationController popViewControllerAnimated:NO];
    [appDelegate.rootNavigationController pushViewController:baseController animated:YES];
    [baseController release];
}

@end
